using Admin.Application.Common;
using Admin.Application.Dto;
using Admin.Application.Dto.Role;
using Admin.Application.Repositories;
using Admin.Domain.Entities;
using Admin.Domain.Repositories;

namespace Admin.Application.Services;

public class RoleService(IRepository<Role> roleRepository,IRepository<Permission> permissionRepository,ISystemLogRepository logService) : IRoleService{
    private readonly IRepository<Role> _roleRepository = roleRepository;
    private readonly IRepository<Permission> _permissionRepository = permissionRepository;
    private readonly ISystemLogRepository _logService = logService;

    public async Task<Result<string>> AddRoleAsync(RoleDto roleDto)
    {
        var role = Role.CreateRole(roleDto.RoleName);
        if (role == null)
        {
            await _logService.AddAsync($"角色创建失败：名称为 {roleDto.RoleName}");
            return Result<string>.Fail("角色创建失败");
        }

        await _roleRepository.AddAsync(role);
        await _logService.AddAsync($"角色创建成功：{roleDto.RoleName}");
        return Result<string>.Success("角色创建成功");
    }

    public async Task<Result<string>> AssignPermissionsToRoleAsync(Guid roleId, Guid permissionId)
    {
        var role = await _roleRepository.GetByIdAsync(roleId);
        var permission = await _permissionRepository.GetByIdAsync(permissionId);
        if (role == null || permission == null)
        {
            await _logService.AddAsync($"角色赋予权限失败：角色或权限不存在 - 角色ID：{roleId}，权限ID：{permissionId}");
            return Result<string>.Fail("角色或权限不存在");
        }

        var isRoleUpdated = role.AssignPermission(permission);
        var isPermissionUpdated = permission.AddRole(role);
        if (!isRoleUpdated || !isPermissionUpdated)
        {
            await _logService.AddAsync($"角色赋予权限失败：更新失败 - 角色ID：{roleId}，权限ID：{permissionId}");
            return Result<string>.Fail("角色赋予权限失败");
        }

        await _roleRepository.UpdateAsync(role);
        await _permissionRepository.UpdateAsync(permission);
        await _logService.AddAsync($"角色赋予权限成功：角色ID：{roleId}，权限ID：{permissionId}");
        return Result<string>.Success("角色赋予权限成功");
    }

    public async Task<Result<string>> DeleteRoleAsync(Guid roleId)
    {
        var role = await _roleRepository.GetByIdAsync(roleId);
        if (role == null)
        {
            await _logService.AddAsync($"删除角色失败：角色不存在 - {roleId}");
            return Result<string>.Fail("角色不存在");
        }

        var isRoleUpdated = role.DeleteRole();
        if (!isRoleUpdated)
        {
            await _logService.AddAsync($"删除角色失败：删除失败 - {roleId}");
            return Result<string>.Fail("角色删除失败");
        }

        await _roleRepository.UpdateAsync(role);
        await _logService.AddAsync($"删除角色成功：{role.RoleName}");
        return Result<string>.Success("角色删除成功");
    }

    public async Task<Result<List<ResRoleDto>>> GetPagedRoleAsync(int pageIndex, int pageSize)
    {
        if (pageIndex < 0 || pageSize < 0)
        {
            await _logService.AddAsync($"分页查询角色失败：无效的页码或数据条数 - 页码：{pageIndex}，条数：{pageSize}");
            return Result<List<ResRoleDto>>.Fail("无效的页码或数据条数");
        }

        var roleList = await _roleRepository.GetPagedAsync(pageIndex, pageSize);

        var resRoleDtoTasks = roleList.Select(r =>
            new ResRoleDto(
                r.Id,
                r.RoleName,
                r.IsActive,
                r.Description,
                string.Join(",", r.Permissions.Select(p => p.PermissionName))
            )
        );

        await _logService.AddAsync($"分页查询角色成功：页码 {pageIndex}，条数 {pageSize}");
        return Result<List<ResRoleDto>>.Success([.. resRoleDtoTasks]);
    }

    public async Task<Result<ResRoleDto?>> GetRoleByIdAsync(Guid roleId)
    {
        var role = await _roleRepository.GetByIdAsync(roleId);
        if (role == null)
        {
            await _logService.AddAsync($"查询角色失败：角色不存在 - {roleId}");
            return Result<ResRoleDto?>.Fail("角色不存在");
        }

        var resRoleDto = new ResRoleDto(
                role.Id,
                role.RoleName,
                role.IsActive,
                role.Description,
                string.Join(",", role.Permissions.Select(r => r.PermissionName))
            );

        await _logService.AddAsync($"查询角色成功：{role.RoleName}");
        return Result<ResRoleDto?>.Success(resRoleDto);
    }

    public async Task<Result<string>> RemovePermissionsFromRoleAsync(Guid roleId, Guid permissionId)
    {
        var role = await _roleRepository.GetByIdAsync(roleId);
        var permission = await _permissionRepository.GetByIdAsync(permissionId);
        if (role == null || permission == null)
        {
            await _logService.AddAsync($"角色移除权限失败：角色或权限不存在 - 角色ID：{roleId}，权限ID：{permissionId}");
            return Result<string>.Fail("角色或权限不存在");
        }

        var isRoleUpdated = role.RemovePermission(permission);
        var isPermissionUpdated = permission.RemoveRole(role);
        if (!isRoleUpdated || !isPermissionUpdated)
        {
            await _logService.AddAsync($"角色移除权限失败：更新失败 - 角色ID：{roleId}，权限ID：{permissionId}");
            return Result<string>.Fail("角色移除权限失败");
        }

        await _roleRepository.UpdateAsync(role);
        await _permissionRepository.UpdateAsync(permission);
        await _logService.AddAsync($"角色移除权限成功：角色ID：{roleId}，权限ID：{permissionId}");
        return Result<string>.Success("角色移除权限成功");
    }

    public async Task<Result<string>> UpdateRoleAsync(Guid roleId, RoleDto roleDto)
    {
        var role = await _roleRepository.GetByIdAsync(roleId);
        if (role == null)
        {
            await _logService.AddAsync($"更新角色信息失败：角色不存在 - {roleId}");
            return Result<string>.Fail("角色不存在");
        }

        bool isRoleUpdated = role.UpdateUserInfo(roleDto.RoleName, roleDto.Description);
        if (!isRoleUpdated)
        {
            await _logService.AddAsync($"更新角色信息失败：更新失败 - {roleId}");
            return Result<string>.Fail("角色信息更新失败");
        }

        await _roleRepository.UpdateAsync(role);
        await _logService.AddAsync($"更新角色信息成功：{role.RoleName}");
        return Result<string>.Success("角色信息更新成功");
    }

    public async Task<Result<string>> UpdateIsActive(Guid userId, ActiveDto activeDto)
    {
        var role = await _roleRepository.GetByIdAsync(userId);
        if (role == null)
        {
            await _logService.AddAsync($"更新角色启用状态失败：角色不存在 - {userId}");
            return Result<string>.Fail("角色不存在");
        }

        bool isRoleUpdated;
        if (activeDto.IsActive)
        {
            isRoleUpdated = role.EnableRole();
        }
        else
        {
            isRoleUpdated = role.DisableRole();
        }

        if (!isRoleUpdated)
        {
            await _logService.AddAsync($"更新角色启用状态失败：更新失败 - {userId}");
            return Result<string>.Fail("角色启用状态更新失败");
        }

        await _roleRepository.UpdateAsync(role);
        await _logService.AddAsync($"更新角色启用状态成功：{role.RoleName}");
        return Result<string>.Success("角色启用状态更新成功");
    }
}